"""
描述:数据库封装,实现数据回滚操作

"""
import pymysql


class DB:
    # 初始化数据库对象和游标对象
    def __init__(self, database, host="localhost",
                 user="root", password="123456",
                 charset="utf8", port=3306,
                 result_type=pymysql.cursors.Cursor):
        self.con = pymysql.connect(
            host=host,
            user=user,
            password=password,
            database=database,
            charset=charset,
            port=port
        )
        self.cursor = self.con.cursor(result_type)
        # 三目运算符
        self.result_type = () if result_type == pymysql.cursors.Cursor else []

    def page_db_read(self, sql):
        """
        读操作
        :return:
        """
        try:
            # 执行sql语句
            self.cursor.execute(sql)
            # 获取结果
            result = self.cursor.fetchall()
            return result
        except Exception:
            return self.result_type

    def page_db_write(self, sql):
        """
        写操作
        :return:
        """
        try:
            rows = self.cursor.execute(sql)
        except Exception:
            self.con.rollback()
            return 0
        else:
            self.con.commit()
            return "操作成功", rows
			
	def page_db_write1(self, sql, name):
			try:
				rows = self.cursor.execute(sql, [name])
			except Exception:
				self.con.rollback()
				return 0
			else:
				self.con.commit()
				return "操作成功", rows			

    def __del__(self):
        # 关闭数据库对象和游标对象
        self.cursor.close()
        self.con.close()


if __name__ == '__main__':
    b = DB("ecshop_db")
